<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
namespace api\api\service;


use think\Db;

class OrderService
{
    /**获取用户订单
     * @param $user_id 用户
     * @param $type 类型
     * @return array|false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    function user_order($user_id, $type, $page)
    {
        if ($type == 100) {//获取全部
            $order = Db::name('order')->where('user_id', $user_id)->page($page, 10)->order('order_id desc')->field('order_id,order_number,type,order_type,user_id,driver_id,pay_status,status,start_district,start_address,end_address,end_district,order_time,start_lon,start_lat,end_lon,end_lat,is_pay_first')->select()->toArray();
        } else if ($type == 90) {//待付款
			$map1 = [
					['is_pay_first', '=', '1'],
					['pay_status', '=', '0'],
					['user_id', '=', $user_id],
					['status', '=', '0'],
				];

			$map2 = [
					['user_id', '=', $user_id],
					['pay_status', '=', '0'],
					['status', '=', '4'],
				];
            $order = Db::name('order')->whereOr([ $map1, $map2 ])->page($page, 10)->order('order_id desc')->field('order_id,order_number,type,order_type,user_id,driver_id,pay_status,status,start_district,start_address,end_address,end_district,order_time,start_lon,start_lat,end_lon,end_lat,is_pay_first')->select()->toArray();
        } else if ($type == 80) {//待评价列表
			$where = [
					['user_id', '=', $user_id],
					['status', '=', '5'],
				];
			$order = Db::name('order')->where($where)->page($page, 10)->order('order_id desc')->field('order_id,order_number,type,order_type,user_id,driver_id,pay_status,status,start_district,start_address,end_address,end_district,order_time,start_lon,start_lat,end_lon,end_lat,is_pay_first')->select()->toArray();

		}

        return $order;
    }

    /**获取订单详情
     * @param $id
     * @return array|false|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    function user_order_id($id)
    {

        $order = Db::name('order')->where('order_id', $id)->find();
        return $order;
    }

    /**订单任务管理
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    function order_task()
    {
        $order = Db::name('order')->where('order_type', 'neq', 6)->where('status', 0)->where('expire_time', '<=', time())->select();
        foreach ($order as $k => $v) {
//            Db::startTrans(); //开启事务
            //订单已经支付执行订单退款操作
            if ($v['pay_status'] == 1) {
//                $allarea['balance'] = Db::raw('balance+' . $v['real_amount']);
//
//                $all_info = Db::name('user')->where('id', $v['user_id'])->update($allarea);
//
//                if ($all_info) {
//
//                    $alluser = Db::name('user')->where('id', $v['user_id'])->find();
//                    userbalanceLog($v['user_id'], 3, $v['type'], +$v['real_amount'], $alluser['balance'], $v['order_number'] . '订单取消支付金额返回余额', $v['order_id'], '');
//
//                }
                if($v['pay_method']==1) {
                    $param = ['out_trade_no' => $v['order_number'], 'total_amount' => $v['real_amount']];
                    $result = hook_one("alipay_order_refund", $param);
                    if ($result['code'] != '10000') {
//                        Db::rollback();
                       return false;
                    }
                }elseif ($v['pay_method']==2){
                    $order_sn_t = 'T' . substr($v['order_sn'], 1);
                    $param = [
                        'out_trade_no' => $v['order_sn'],     //系统内部订单号
                        'out_refund_no' => $order_sn_t,  //内部的退款单号
                        'total_fee' => 0.01,     //订单总金额
                        'refund_fee' => 0.01    //退款总金额
                    ];
                    $result = hook_one('create_refund', $param);

                    // $param = ['out_trade_no' => $order_sn, 'total_amount' => 0.01];
                    // $result = hook_one("alipay_order_refund", $param);
                    if ($result['return_code'] != 'SUCCESS' || $result['result_code'] != 'SUCCESS') {
                        Db::rollback();
                        $this->error("订单取消失败");
                    }
                }
            }
            $remark_msg = '您的订单(' . $v['order_number'] . ')超时已被取消';
            Db::name('order')->where('order_id', $v['order_id'])->update(array('cancel_time' => time(), 'cancel_reason_id' => 6, 'cancel_party' => 3, 'status' => 6));
            $user = Db::name('user')->where('id', $v['user_id'])->find();
            if ($user['allow_push'] == 1) {
                $param = [
                    'type' => 1,
                    'registration_id' => $user['jpush_id'],
                    'msg' => $remark_msg
                ];
                $res = hook_one('jpush_send', $param);
            }
            create_user_message(1,$v['user_id'], '取消订单', $remark_msg, $remark_msg);
//            Db::commit();
        }
        return true;
    }

    /**定时自动派单
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
function order_send(){

//自动派单
    $orderlist = Db::name('order')->where('order_type', 'neq', 6)->where('status', 0)->where('expire_time', '>=', time())->where('send_order_time', '<=', time())->select();

    foreach ($orderlist as $k => $order) {

        if ($order['type'] == 1) {
            //超过时间可以派单

            if ($order['send_order_time'] <= time()) {
                if ($order['is_pay_first'] == 0){
                    //常用司机座位 5 7 以上
                    if ($order['order_type'] == 10) {
                        $dataorders = array();
                        //拼车逻辑
                        //查询正常接单的司机
                        $driver = Db::name('driver_user')->where(array('driver_type' => 5, 'work_status' => 1, 'user_status' => 2))->where('', 'exp', Db::raw("FIND_IN_SET(" . $order['line_id'] . ",lind)"))->select();
                        foreach ($driver as $k => $v) {
                            $car = array();
                            if ($v['car_lat'] != '' && $v['car_lon'] != '') {
                                $uu = 'http://api.map.baidu.com/routematrix/v2/driving?output=json&origins=' . $order['start_lat'] . ',' . $order['start_lon'] . '&destinations=' . $v['car_lat'] . ',' . $v['car_lon'] . '&ak=bPUIKczaCFnVGlHD7cgalCeW0pKDhDq9';
                                $ch = curl_init($uu);
                                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                                $cexeCute = curl_exec($ch);
                                curl_close($ch);
                                $distance_ = json_decode($cexeCute, true);
                                $car = $v;

                                if ($distance_['status'] == 0) {

                                    $car['distance'] = number_format($distance_['result'][0]['distance']['value'] / 1000, 2);
                                    //查询如果已经有包车则不允许拼车
                                    $order_type = Db::name('order')->where('status', '>=', 1)->where('status', '<', 4)->where('driver_id', $v['id'])->where('order_type', '>', 10)->field('order_type')->find();
                                    //已经派单并且退单过
                                    $other = stripos($order['re_user'], $v['id'] . ",");
                                    if (!$order_type && $other === false) {
                                        $ride = Db::name('order')->where('status', '>=', 1)->where('status', '<', 4)->where('order_group_id',0)->where('driver_id', $v['id'])->sum('ride');
                                        if (($v['car_seats_num'] - $ride - 1) >= $order['ride']) {
                                            array_push($dataorders, $car);
                                        }
                                    }
                                }
                            }
                        }
                        $last_names = array_column($dataorders, 'distance');
                        array_multisort($last_names, SORT_ASC, $dataorders);
                        if (count($dataorders) > 0) {
                            $driver_user = $dataorders[0];
                            $status = Db::name('order')->where('order_id', $order['order_id'])->update(array('driver_id' => $driver_user['id'], 'is_appoint' => 0, 'driver_start_time' => time(), 'status' => 1));
                            if ($status) {
                                create_user_message(2, $driver_user['id'], '订单指派', '您有新订单被指派，请查看', '您有新订单被指派，请查看');
                                if ($driver_user['jpush_id'] != '') {
                                    $param = [
                                        'type' => 2,
                                        'registration_id' => $driver_user['jpush_id'],
                                        'msg' => '您有新订单被指派，请查看'
                                    ];
                                    $res = hook_one('jpush_send', $param);
                                }
                            }
                        }
                    } else {

                        //包车分配逻辑
                        //查询正常接单的司机
                        if ($order['ride'] < 5) {
                            $driver = Db::name('driver_user')->where(array('driver_type' => 5, 'work_status' => 1, 'user_status' => 2))->where('car_seats_num', '<=', '5')->where('', 'exp', Db::raw("FIND_IN_SET(" . $order['line_id'] . ",lind)"))->select();
                        } else if ($order['ride'] > 5 || $order['ride'] < 7) {
                            $driver = Db::name('driver_user')->where(array('driver_type' => 5, 'work_status' => 1, 'user_status' => 2))->where('car_seats_num', '>', '5')->where('car_seats_num', '<=', '7')->where('', 'exp', Db::raw("FIND_IN_SET(" . $order['line_id'] . ",lind)"))->select();
                        } else if ($order['ride'] > 7) {
                            $driver = Db::name('driver_user')->where(array('driver_type' => 5, 'work_status' => 1, 'user_status' => 2))->where('car_seats_num', '>', '7')->where('', 'exp', Db::raw("FIND_IN_SET(" . $order['line_id'] . ",lind)"))->select();
                        }
                        //$driver = Db::name('driver_user')->where(array('driver_type' => 5, 'work_status' => 1, 'user_status' => 2))->select();
                        $dataorders = get_driver($driver, $order);

//        logResult(json_encode($dataorders));
                        $last_names = array_column($dataorders, 'distance');
                        array_multisort($last_names, SORT_ASC, $dataorders);
                        if (count($dataorders) > 0) {
                            $driver_user = $dataorders[0];
                            $status = Db::name('order')->where('order_id', $order['order_id'])->update(array('driver_id' => $driver_user['id'], 'is_appoint' => 0, 'driver_start_time' => time(), 'status' => 1));
                            if ($status) {
                                Db::name('driver_user')->where('id', $driver_user['id'])->update(array('work_status' => 2));
                                create_user_message(2, $driver_user['id'], '订单指派', '您有新订单被指派，请查看', '您有新订单被指派，请查看');
                                if ($driver_user['jpush_id'] != '') {
                                    $param = [
                                        'type' => 2,
                                        'registration_id' => $driver_user['jpush_id'],
                                        'msg' => '您有新订单被指派，请查看'
                                    ];
                                    $res = hook_one('jpush_send', $param);
                                }
                            }
                        } else {
                            //二次派单
                            if ($order['ride'] < 5) {
                                $driver = Db::name('driver_user')->where(array('driver_type' => 5, 'work_status' => 1, 'user_status' => 2))->where('car_seats_num', '>', '5')->where('car_seats_num', '<=', '7')->where('', 'exp', Db::raw("FIND_IN_SET(" . $order['line_id'] . ",lind)"))->select();
                            } else if ($order['ride'] < 7) {
                                $driver = Db::name('driver_user')->where(array('driver_type' => 5, 'work_status' => 1, 'user_status' => 2))->where('car_seats_num', '>', '7')->where('', 'exp', Db::raw("FIND_IN_SET(" . $order['line_id'] . ",lind)"))->select();
                            }
                            $dataorderser = get_driver($driver, $order);
                            $last_names = array_column($dataorderser, 'distance');
                            array_multisort($last_names, SORT_ASC, $dataorderser);
                            if (count($dataorderser) > 0) {
                                $driver_user = $dataorderser[0];
                                $status = Db::name('order')->where('order_id', $order['order_id'])->update(array('driver_id' => $driver_user['id'], 'is_appoint' => 0, 'driver_start_time' => time(), 'status' => 1));
                                if ($status) {
                                    Db::name('driver_user')->where('id', $driver_user['id'])->update(array('work_status' => 2));
                                    create_user_message(2, $driver_user['id'], '订单指派', '您有新订单被指派，请查看', '您有新订单被指派，请查看');
                                    if ($driver_user['jpush_id'] != '') {
                                        $param = [
                                            'type' => 2,
                                            'registration_id' => $driver_user['jpush_id'],
                                            'msg' => '您有新订单被指派，请查看'
                                        ];
                                        $res = hook_one('jpush_send', $param);
                                    }
                                }
                            }
                        }
                    }
            }else{
                    if($order['pay_status']==1){
                        //常用司机座位 5 7 以上
                        if ($order['order_type'] == 10) {
                            $dataorders = array();
                            //拼车逻辑
                            //查询正常接单的司机
                            $driver = Db::name('driver_user')->where(array('driver_type' => 5, 'work_status' => 1, 'user_status' => 2))->where('', 'exp', Db::raw("FIND_IN_SET(" . $order['line_id'] . ",lind)"))->select();
                            foreach ($driver as $k => $v) {
                                $car = array();
                                if ($v['car_lat'] != '' && $v['car_lon'] != '') {
                                    $uu = 'http://api.map.baidu.com/routematrix/v2/driving?output=json&origins=' . $order['start_lat'] . ',' . $order['start_lon'] . '&destinations=' . $v['car_lat'] . ',' . $v['car_lon'] . '&ak=bPUIKczaCFnVGlHD7cgalCeW0pKDhDq9';
                                    $ch = curl_init($uu);
                                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                                    $cexeCute = curl_exec($ch);
                                    curl_close($ch);
                                    $distance_ = json_decode($cexeCute, true);
                                    $car = $v;

                                    if ($distance_['status'] == 0) {

                                        $car['distance'] = number_format($distance_['result'][0]['distance']['value'] / 1000, 2);
                                        //查询如果已经有包车则不允许拼车
                                        $order_type = Db::name('order')->where('status', '>=', 1)->where('status', '<', 4)->where('driver_id', $v['id'])->where('order_type', '>', 10)->field('order_type')->find();
                                        //已经派单并且退单过
                                        $other = stripos($order['re_user'], $v['id'] . ",");
                                        if (!$order_type && $other === false) {
                                            $ride = Db::name('order')->where('status', '>=', 1)->where('status', '<', 4)->where('driver_id', $v['id'])->sum('ride');
                                            if (($v['car_seats_num'] - $ride - 1) >= $order['ride']) {
                                                array_push($dataorders, $car);
                                            }
                                        }
                                    }
                                }
                            }
                            $last_names = array_column($dataorders, 'distance');
                            array_multisort($last_names, SORT_ASC, $dataorders);

                            if (count($dataorders) > 0) {
                                $driver_user = $dataorders[0];
                                $status = Db::name('order')->where('order_id', $order['order_id'])->update(array('driver_id' => $driver_user['id'], 'is_appoint' => 0, 'driver_start_time' => time(), 'status' => 1));
                                if ($status) {
                                    create_user_message(2, $driver_user['id'], '订单指派', '您有新订单被指派，请查看', '您有新订单被指派，请查看');
                                    if ($driver_user['jpush_id'] != '') {
                                        $param = [
                                            'type' => 2,
                                            'registration_id' => $driver_user['jpush_id'],
                                            'msg' => '您有新订单被指派，请查看'
                                        ];
                                        $res = hook_one('jpush_send', $param);
                                    }
                                }
                            }
                        } else {

                            //包车分配逻辑
                            //查询正常接单的司机
                            if ($order['ride'] < 5) {
                                $driver = Db::name('driver_user')->where(array('driver_type' => 5, 'work_status' => 1, 'user_status' => 2))->where('car_seats_num', '<=', '5')->where('', 'exp', Db::raw("FIND_IN_SET(" . $order['line_id'] . ",lind)"))->select();
                            } else if ($order['ride'] > 5 || $order['ride'] < 7) {
                                $driver = Db::name('driver_user')->where(array('driver_type' => 5, 'work_status' => 1, 'user_status' => 2))->where('car_seats_num', '>', '5')->where('car_seats_num', '<=', '7')->where('', 'exp', Db::raw("FIND_IN_SET(" . $order['line_id'] . ",lind)"))->select();
                            } else if ($order['ride'] > 7) {
                                $driver = Db::name('driver_user')->where(array('driver_type' => 5, 'work_status' => 1, 'user_status' => 2))->where('car_seats_num', '>', '7')->where('', 'exp', Db::raw("FIND_IN_SET(" . $order['line_id'] . ",lind)"))->select();
                            }
                            //$driver = Db::name('driver_user')->where(array('driver_type' => 5, 'work_status' => 1, 'user_status' => 2))->select();
                            $dataorders = get_driver($driver, $order);

//        logResult(json_encode($dataorders));
                            $last_names = array_column($dataorders, 'distance');
                            array_multisort($last_names, SORT_ASC, $dataorders);
                            if (count($dataorders) > 0) {
                                $driver_user = $dataorders[0];
                                $status = Db::name('order')->where('order_id', $order['order_id'])->update(array('driver_id' => $driver_user['id'], 'is_appoint' => 0, 'driver_start_time' => time(), 'status' => 1));
                                if ($status) {
                                    Db::name('driver_user')->where('id', $driver_user['id'])->update(array('work_status' => 2));
                                    create_user_message(2, $driver_user['id'], '订单指派', '您有新订单被指派，请查看', '您有新订单被指派，请查看');
                                    if ($driver_user['jpush_id'] != '') {
                                        $param = [
                                            'type' => 2,
                                            'registration_id' => $driver_user['jpush_id'],
                                            'msg' => '您有新订单被指派，请查看'
                                        ];
                                        $res = hook_one('jpush_send', $param);
                                    }
                                }
                            } else {
                                //二次派单
                                if ($order['ride'] < 5) {
                                    $driver = Db::name('driver_user')->where(array('driver_type' => 5, 'work_status' => 1, 'user_status' => 2))->where('car_seats_num', '>', '5')->where('car_seats_num', '<=', '7')->where('', 'exp', Db::raw("FIND_IN_SET(" . $order['line_id'] . ",lind)"))->select();
                                } else if ($order['ride'] < 7) {
                                    $driver = Db::name('driver_user')->where(array('driver_type' => 5, 'work_status' => 1, 'user_status' => 2))->where('car_seats_num', '>', '7')->where('', 'exp', Db::raw("FIND_IN_SET(" . $order['line_id'] . ",lind)"))->select();
                                }
                                $dataorderser = get_driver($driver, $order);
                                $last_names = array_column($dataorderser, 'distance');
                                array_multisort($last_names, SORT_ASC, $dataorderser);
                                if (count($dataorderser) > 0) {
                                    $driver_user = $dataorderser[0];
                                    $status = Db::name('order')->where('order_id', $order['order_id'])->update(array('driver_id' => $driver_user['id'], 'is_appoint' => 0, 'driver_start_time' => time(), 'status' => 1));
                                    if ($status) {
                                        Db::name('driver_user')->where('id', $driver_user['id'])->update(array('work_status' => 2));
                                        create_user_message(2, $driver_user['id'], '订单指派', '您有新订单被指派，请查看', '您有新订单被指派，请查看');
                                        if ($driver_user['jpush_id'] != '') {
                                            $param = [
                                                'type' => 2,
                                                'registration_id' => $driver_user['jpush_id'],
                                                'msg' => '您有新订单被指派，请查看'
                                            ];
                                            $res = hook_one('jpush_send', $param);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return true;
        }else if($order['type'] == 3){
            if ($order['send_order_time'] <= time()) {
                //常用司机座位 5 7 以上

                $dataorders = array();
                //拼车逻辑
                //查询正常接单的快件司机
                $driver = Db::name('driver_user')->where(array('driver_type' => 5, 'work_status' => 1, 'user_status' => 2,'can_express'=>1))->where('', 'exp', Db::raw("FIND_IN_SET(" . $order['line_id'] . ",lind)"))->select();
                foreach ($driver as $k => $v) {
                    $car = array();
                    if ($v['car_lat'] != '' && $v['car_lon'] != '') {
                        $uu = 'http://api.map.baidu.com/routematrix/v2/driving?output=json&origins=' . $order['start_lat'] . ',' . $order['start_lon'] . '&destinations=' . $v['car_lat'] . ',' . $v['car_lon'] . '&ak=bPUIKczaCFnVGlHD7cgalCeW0pKDhDq9';
                        $ch = curl_init($uu);
                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                        $cexeCute = curl_exec($ch);
                        curl_close($ch);
                        $distance_ = json_decode($cexeCute, true);
                        $car = $v;

                        if ($distance_['status'] == 0) {

                            $car['distance'] = number_format($distance_['result'][0]['distance']['value'] / 1000, 2);
                            //查询如果已经有包车则不允许拼车
                            $order_type = Db::name('order')->where('status', '>=', 1)->where('status', '<', 4)->where('driver_id', $v['id'])->where('order_type', 11)->field('order_type')->find();
                            //已经派单并且退单过
                            $other = stripos($order['re_user'], $v['id'] . ",");

                            if (!$order_type && $other === false) {
                                $ride = Db::name('order')->where('status', '>=', 1)->where('status', '<', 4)->where('driver_id', $v['id'])->where('order_group_id',0)->count();

                                if (($v['kuai_num'] - $ride ) >= 1) {
                                    array_push($dataorders, $car);
                                }
                            }
                        }
                    }
                }
                $last_names = array_column($dataorders, 'distance');
                array_multisort($last_names, SORT_ASC, $dataorders);

                if (count($dataorders) > 0) {
                    $driver_user = $dataorders[0];
                    $status = Db::name('order')->where('order_id', $order['order_id'])->update(array('driver_id' => $driver_user['id'], 'is_appoint' => 0, 'driver_start_time' => time(), 'status' => 1));
                    if ($status) {
                        create_user_message(2, $driver_user['id'], '订单指派', '您有新订单被指派，请查看', '您有新订单被指派，请查看');
                        if ($driver_user['jpush_id'] != '') {
                            $param = [
                                'type' => 2,
                                'registration_id' => $driver_user['jpush_id'],
                                'msg' => '您有新订单被指派，请查看'
                            ];
                            $res = hook_one('jpush_send', $param);
                        }
                    }
                }
            }
            return true;
        }
    }
}
    /**更改订单状态
     * @param $user_id
     * @param $order_id
     * @param $status
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    function update_order($user_id, $order_id, $status)
    {
       $ret= Db::name('order')->where('user_id', $user_id)->where('order_id', $order_id)->update(array('status' => $status));
       if($ret){
           return true;
       }else{
           return false;
       }
    }

}
